package com.winter.main.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.winter.main.model.data.ExcelData;
import com.winter.main.service.BaiduAuthService;
import com.winter.main.utils.Base64ImgUtil;
import com.winter.main.utils.ExcelUtils;
import com.winter.main.utils.HttpUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Desc:
 * Author: dushuang
 * Date: Create in 2018/5/3
 */
@Controller
@RequestMapping("/excel")
public class ExcelController {

    private Logger logger = LogManager.getLogger(this);

    /**
     * 识别身份证,返回表格
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/identifyImg",method = RequestMethod.GET)
    public void excel(HttpServletResponse response) throws Exception {
        File file = ResourceUtils.getFile("classpath:file/ssssss-6.xlsx");
        //File file = new File("D:\\ssssss.xlsx");
        FileInputStream fis = new FileInputStream(file);
        if (file.exists()) {
            Workbook wb = null;
            final String baiduAccessToken = BaiduAuthService.getAuth();
            final String idCardSide = "front";
            if(ExcelUtils.isExcel2007(file.getPath())){
                wb = new XSSFWorkbook(fis);
            }else{
                wb = new HSSFWorkbook(fis);
            }
            // 确定生成excel 的格式
            ExcelData excelData = new ExcelData();
            excelData.setName("ocr");
            // 标题
            List<String> titles = new ArrayList<>();
            titles.add("身份证号");
            titles.add("地址");
            excelData.setTitles(titles);
            // 数据
            List<List<Object>> rows = new ArrayList();

            Sheet sheet = wb.getSheetAt(0);//获取第一张表
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                logger.info("######已进行到第 "+i+" 行######");
                Row row = sheet.getRow(i);//获取索引为i的行，以0开始
                String idcardImg = row.getCell(0).getStringCellValue();//获取第i行的索引为0的单元格数据
                logger.info("获取表格身份证图片: " + idcardImg);
                if(idcardImg != null){
                    String base64Img = Base64ImgUtil.GetImageStrFromUrl(idcardImg);
                    //String base64Img = Base64ImgUtil.GetImageStrFromPath("E:\\workspace\\sunshine\\src\\main\\resources\\file\\9458888_02.jpg");
                    //logger.info("图片BASE64结果: " + base64Img);
                    List<Object> content = new ArrayList();
                    if("".equals(base64Img)){
                        content.add("");
                        rows.add(content);
                        continue;
                    }
                    String result = BaiduAuthService.identifyIdCard(baiduAccessToken,idCardSide,base64Img);
                    logger.info(JSON.parseObject(result));
                    JSONObject cardInfo = JSON.parseObject(result);
                    if(cardInfo.containsKey("words_result") && cardInfo.containsKey("words_result_num")){
                        JSONObject wordResult = cardInfo.getJSONObject("words_result");
                        String location = "";
                        if(wordResult.containsKey("住址")){
                            JSONObject locationResult = wordResult.getJSONObject("住址");
                            location = locationResult.getString("words");
                        }
                        String no = "";
                        if(wordResult.containsKey("公民身份号码")){
                            JSONObject noResult = wordResult.getJSONObject("公民身份号码");
                            no = noResult.getString("words");
                        }
                        content.add(no);
                        content.add(location);
                        rows.add(content);
                    }else{
                        content.add("");
                        rows.add(content);
                        continue;
                    }
                }

            }
            excelData.setRows(rows);
            logger.info("OCR识别结束,返回数据");
            // 生成表格
            SimpleDateFormat fdate=new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
            String fileName=fdate.format(new Date())+".xls";
            ExcelUtils.exportExcel(response,fileName,excelData);

        }
    }

}
